package com.qjq.glasses_shopping.controller;


import com.qjq.glasses_shopping.pojo.CartGoods;
import com.qjq.glasses_shopping.pojo.Orders;
import com.qjq.glasses_shopping.result.BaseResult;
import com.qjq.glasses_shopping.service.CartService;
import com.qjq.glasses_shopping.service.OrdersService;
import com.qjq.glasses_shopping.util.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/orders")
public class OrdersController {
    @Resource
    private OrdersService ordersService;
    @Resource
    private CartService cartService;


    @PostMapping("/add")
    public BaseResult<Orders> add(@RequestBody Orders orders, @RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ","");
        Map<String, Object> verify = JwtUtils.verify(token);
        Long userId = (Long) verify.get("userId");
        //保存订单
        orders.setUserId(userId);
        ordersService.add(orders);
        //从购物车中删除已购买的商品
        List<CartGoods> cartGoods = orders.getCartGoods();
        for (CartGoods cartGood : cartGoods) {
            cartService.deleteCartOption(userId, cartGood.getGoodId());
        }
        return BaseResult.ok(orders);
    }

    /**
     * 根据id查询订单
     * @param id 订单id
     * @return 查询结果
     */
    @GetMapping("/findById")
    public BaseResult<Orders> findById(String id){
        Orders orders = ordersService.findById(id);
        return BaseResult.ok(orders);
    }

    /**
     * 查询用户的订单
     * @param status 订单状态：1.未付款 2.已付款 3.未发货 4.已发货 5.交易成功 6.交易关闭 7.待评价，传入空值代表查询所有
     * @param authorization authorization
     * @return 查询结果
     */
    @GetMapping("/findUserOrders")
    public BaseResult<List<Orders>> findUserOrders(Integer status,@RequestHeader("Authorization") String authorization){
        String token = authorization.replace("Bearer ","");
        Map<String, Object> verify = JwtUtils.verify(token);
        Long userId = (Long) verify.get("userId");
        List<Orders> orders = ordersService.findUserOrders(userId, status);
        return BaseResult.ok(orders);
    }
}
